import {reqCartList,reqDeleteCartById,reUpdateCheckedByid} from "@/api/index"

const state={
   cartList:[]
}
const mutations={
  CARTLIST(state,data){
   
    state.cartList=data[0].cartInfoList

  },
}
const actions={
  //修改商品全部状态
  updateAllCartIsChecked({dispatch,state},isChecked){
      let promiseAll = [];
      state.cartList.forEach((item) => {
      
        let promise = dispatch("updataCheckedByid", {
          skuId: item.skuId,
          isChecked,
        
        });
        console.log(promise)
        promiseAll.push(promise);
      });
      dispatch("getCartList")
      //最终返回结果
      return Promise.all(promiseAll);
    },
      
  
  //删除所有商品
      deleteAllCart({dispatch,state}){
        let PromiseAll = [];
        
      state.cartList.forEach(item => {
        let promise =
        item.isChecked == 1
          ? dispatch("deleteCartList", item.skuId)
          : "";
      //将每一次返回的Promise添加到数组当中
      PromiseAll.push(promise);
      });
      return Promise.all(PromiseAll);
  },
  //获取购物车数据
 async getCartList({commit,state}){
   let result=await reqCartList() 

    if(result.code==200){
      if(result.data==""){
          state.cartList=[]
     }else{
      commit("CARTLIST",result.data)
    }
  }
 },
 //删除一条购物车
async deleteCartList({ commit }, skuId) {
  let result = await reqDeleteCartById(skuId);
  if (result.code == 200) {
    return "ok";
  } else {
    return Promise.reject(new Error("faile"));
  }
},
 //勾选购物车按钮
 async updataCheckedByid({commit},{skuId,isChecked}){
  let result= await reUpdateCheckedByid(skuId,isChecked)
  if(result.code==200){
    return "ok"
  }else{
    return Promise.reject(new Error("faile"))
  }
}
}
const getters={
}

export default{
  state,
  mutations,
  actions,
  getters
}